from django.core.context_processors import csrf
from django.forms.models import formset_factory
from django.forms.models import modelformset_factory
from django.shortcuts import get_object_or_404
from django.shortcuts import render_to_response as r2r
from django.template import RequestContext

from forms.models import Field, Form

from searches.models import SearchForm

def index(request):
    c = {}
    c.update(csrf(request))
    sf = SearchForm()
    c.update({'searchform': sf})
    return r2r('searches/index.html', c)

def results(request):
    c = {}
    c.update(csrf(request))
    if request.method == 'POST': 
        sf = SearchForm(request.POST)
        if sf.is_valid():
            words = sf.cleaned_data['keywords']           
        else:
            sf = SearchForm()
            words = ''
        search_result_list = Form.objects.filter(keywords__icontains=words).order_by('-ranking')
        c.update({'search_result_list': search_result_list})
        return r2r('searches/results.html', c)
            
def apply(request):
    c = {}
    c.update(csrf(request))
    if request.method == 'POST': 
        form_id_list = request.POST.getlist('selected_form_list')
        field_list = []
        form_list = []
        for form_id in form_id_list:
            form_list.append(Form.objects.get(id=form_id))
            field_list.append(Field.objects.filter(form=form_id))
        #fl = [item for sublist in field_list for item in sublist] # Convert list of lists to list
        c.update({'form_list': form_list})
        c.update({'field_list': field_list})
        return r2r('searches/apply.html', c)
            
def confirm(request):
    pass
    
def whatsnext(request):
    pass
    